<script setup>
import {
  GetListAPI,
  AddDataAPI,
  GetViewAPI,
  EditDataAPI,
  DelDataAPI,
  AddModeDataAPI,
  GetCollectLogListAPI,
  GetPrintInfoAPI,
  GetWarmingAPI,
} from "@/api/device/equipment.js";
import { GetDeptPI } from "@/api/common/index";
import useMqtt from "@/utils/mqtt/index";
import useUserStore from "@/store/modules/user";

// import { GetDeptPI } from '@/api/system/shopAdministration/equipment'
import Form from "./form.vue";
import PhysicalModel from "./physicalModel.vue";
import TextItem from "./textItem.vue";
const { proxy } = getCurrentInstance();
// 封装 方法 字典查询
const { device_status, equipment_operation_status } = proxy.useDict(
  "device_status",
  "equipment_operation_status"
);
/**
 * 定时器
 */
const intervalId = ref(null);
// 回显数据
const ruleForm = ref({});

//表单ref
const formRef = ref(null);

/**
 * 展示状态
 */
const tableType = ref("1");

// 表格数据
const tableData = ref([]);

// 按钮枚举
const btnList = ref([]);
//状态
const state = reactive({
  title: "新增",
  loading: false, // 表格加载状态
  total: 0, // 列表总数量
  ids: [], // 勾选id
  rows: [], // 勾选数据
  btnLoading: false, // 保存按钮加载
  isShow: false, // 弹窗
  singleDis: false, // 多选后禁用
  multipleDis: false, // 没有选择后禁用
  gatherShow: false, //采集弹窗
});

// 分页参数
const query = reactive({
  pageNum: 1,
  pageSize: 10,
});
/**
 * 采集分页
 */
const gatherQuery = reactive({
  pageNum: 1,
  pageSize: 10,
});

// 采集表格数据
const gatherData = ref([]);
const deptData = ref([]);

/**
 * 采集查询
 */
const gatherSelect = ref([
  {
    label: "时间选择",
    type: "时间选择",
  },
]);

// 查询枚举
const selectList = ref([
  {
    label: "设备名称",
    model: "deviceName",
    type: "输入框",
  },
  {
    label: "设备编码",
    model: "deviceCode",
    type: "输入框",
  },
  {
    label: "安装地点",
    model: "installationLocationName",
    type: "安装地点",
  },
  {
    label: "使用部门",
    model: "deviceDept",
    type: "树结构下拉",
    opt: deptData,
    config: { value: "id", label: "label" },
  },
]);

/**
 * 监听
 */
const watchSwitch = ref(2);

const gatherList = ref([]);
/**
 * 采集枚举
 */
const gatherColumn = ref([
  { label: "采集时间", prop: "ts", width: "auto" },
  { label: "采集信息", prop: "msg", width: "auto" },
]);
// 列表枚举
const column = ref([
  { label: "设备名称", prop: "deviceName", width: "100" },
  { label: "设备状态", prop: "deviceStatus", width: "120" },
  // { label: "升温状态", prop: "warmingStatus", width: "100" },
  { label: "运行状态", prop: "equipmentOperationStatus", width: "100" },

  { label: "设备编码", prop: "deviceCode", width: "100" },
  { label: "设备类型", prop: "deviceType", width: "100" },
  // { label: '设备型号', prop: 'deviceUnitType' },
  // { label: '出厂编码', prop: 'factoryCode' },
  { label: "制造厂商", prop: "factoryName", width: "100" },
  { label: "出厂编码", prop: "factoryCode", width: "100" },
  { label: "设备价格", prop: "deviceCost", width: "100" },
  { label: "残值", prop: "deviceSalvage", width: "100" },

  // { label: '出厂年月', prop: 'factoryDate' },
  { label: "安装时间", prop: "installationTime", width: "100" },
  // { label: '投产时间', prop: 'streamTime' },
  { label: "使用部门", prop: "deviceDeptDict", width: "100" },
  { label: "安装地点", prop: "installationLocationName", width: "100" },
  { label: "备注", prop: "remark", width: "100" },
  { label: "创建人", prop: "createMan", width: "100" },
  { label: "创建时间", prop: "createTime", width: "100" },
  { label: "操作", prop: "x", width: "400px" },
]);

// 初始化按钮
const initBtn = () => {
  btnList.value = [
    {
      label: "新增",
      type: "add",
      hasPermi: "device:equipment:add",
    },
    // { type: "import", hasPermi: "device:equipment:import" },
  ];
};

// 勾选列表数据时
const handleSelectionChange = ({ ids, row }) => {
  state.ids = ids;
  state.rows = row;
  state.multipleDis = !row.length;
  state.singleDis = row.length != 1;
  initBtn();
};
handleSelectionChange({ ids: [], row: [] });

// 条件查询
const selectSubmit = (val) => {
  Object.keys(val).forEach((t) => (query[t] = val[t]));
  query.pageNum = 1;
  query.pageSize = 10;
  getList();
};

const gatherSubmit = (val) => {
  watchSwitch.value = 2;
  gatherList.value = [];
  Object.keys(val).forEach((t) => (gatherQuery[t] = val[t]));
  gatherQuery.pageNum = 1;
  gatherQuery.pageSize = 10;
  getgatherList();
};

//新增弹窗
const addDic = () => {
  state.title = "新增";
  state.isShow = true;
};

//修改弹窗
const editDic = async (id) => {
  console.log(proxy.loading);

  proxy.loading();
  try {
    const { data: result } = await GetViewAPI(id);
    ruleForm.value = result;
    state.title = "修改";
    state.isShow = true;
  } catch (error) {
  } finally {
    proxy.closeLoading();
  }
};

//查看弹窗
const lookDic = async (id) => {
  proxy.loading();
  try {
    const { data: result } = await GetViewAPI(id);
    ruleForm.value = result;
    state.title = "查看";
    state.isShow = true;
  } catch (error) {
  } finally {
    proxy.closeLoading();
  }
};

/**
 * 打印获取
 */
const printDic = async (id) => {
  proxy.loading();
  try {
    const { data: result } = await GetPrintInfoAPI(id);
    ruleForm.value = result;
    state.printShow = true;
  } catch (error) {
  } finally {
    proxy.closeLoading();
  }
};

/**
 * 物模型弹窗
 */
const physicalModelDic = async (id) => {
  proxy.loading();
  try {
    const { data: result } = await GetViewAPI(id);
    ruleForm.value = result;
    state.title = "物模型";
    state.physicalModelShow = true;
  } catch (error) {
  } finally {
    proxy.closeLoading();
  }
};

// 关闭弹窗
const close = () => {
  state.isShow = false;
  Object.keys(ruleForm.value).forEach((t) => (ruleForm.value[t] = ""));
  state.gatherShow = false;
  watchSwitch.value = 2;
  // clearInterval(intervalId.value)
};

// 新增提交
const addSub = async () => {
  const result = await proxy.$refs.formRef.submit();
  console.log(result, "result");
  if (!result) return;
  state.btnLoading = true;
  try {
    await AddDataAPI(result);
    proxy.successMsg("新增成功!");
    close();
    getList();
  } catch {
  } finally {
    state.btnLoading = false;
  }
};

// 修改提交
const editSub = async () => {
  const result = await proxy.$refs.formRef.submit();
  if (!result) return;
  state.btnLoading = true;
  try {
    await EditDataAPI(result);
    proxy.successMsg("修改成功!");
    close();
    getList();
  } catch {
  } finally {
    state.btnLoading = false;
  }
};

//删除
const remove = async (id) => {
  proxy.loading();
  try {
    const MesBox = await proxy.DelMessageBox();
    if (!MesBox) return;
    await DelDataAPI(id);
    proxy.successMsg("删除成功!");
    getList();
  } catch (error) {
  } finally {
    proxy.closeLoading();
  }
};

//批量删除
const batchRemove = async () => {
  proxy.loading();
  try {
    await DelDataAPI({ ids: state.ids });
    proxy.successMsg("删除成功!");
    getList();
  } catch (error) {
  } finally {
    proxy.closeLoading();
  }
};

// 获取部门
const getDept = async () => {
  try {
    const res = await GetDeptPI();
    deptData.value = res.data;
  } catch {
  } finally {
  }
};

getDept();

const handleSortChange = (val) => {
  console.log(val, "val");
};

/**
 * 列表切换
 */
const chengeTable = () => {
  query.pageNum = 1;
  query.pageSize = 10;
  tableData.value = [];
  console.log(tableType.value);
  if (tableType.value == 1) {
    getList();
  } else {
    query.pageNum = 0;
    load();
  }
  console.log(tableData.value, " tableData.value");
};

/**
 * 无限滚动
 */
const noMore = computed(() => tableData.value.length >= state.total);
const loadDisabled = computed(() => state.loading || noMore.value);
const load = async () => {
  if (tableData.value.length + 1 >= Number(state.total)) return false;
  state.loading = true;
  try {
    query.pageNum += 1;
    const result = await GetListAPI(query);
    tableData.value = [...tableData.value, ...result.rows];
    state.total = result.total;
  } catch {
  } finally {
    state.loading = false;
  }
};

/**
 * 获取列表
 */
const getgatherList = async () => {
  state.loading = true;
  try {
    const results = await GetCollectLogListAPI(gatherQuery);
    gatherList.value = gatherList.value.concat(results.rows);
    // state.total = results.total
    state.gatherShow = true;
  } catch {
  } finally {
    state.loading = false;
  }
};

/**
 * 采集详情
 */
const gatherDic = async (v) => {
  gatherList.value = [];
  const { data: result } = await GetViewAPI(v.id);
  gatherQuery.deviceKey = "tneQBaTV";
  getgatherList();
  // useMqtt(`/aaa/gather`).initData()
};

/**
 * 执行打印
 */
const printSub = () => {
  proxy.$refs.viewRef.print(ruleForm.value);
};

/**
 * 监听开关
 */
const watchChange = (v) => {
  console.log(v);
  gatherQuery.pageNum = 1;
  gatherList.value = [];
  if (v == 1) {
    useMqtt(`/device/gather`).initData();
  } else if (v == 2) {
    getgatherList();
  }
};
onUnmounted(() => {
  // clearInterval(intervalId.value)
});

/**
 *滚动加载
 */
const loadGather = () => {
  // console.log('---', watchSwitch.value)
  console.log("---");

  if (watchSwitch.value == 2) {
    gatherQuery.pageNum++;
    getgatherList();
  }
};
/**
 * 获取列表
 */
const getList = async () => {
  state.loading = true;
  try {
    const result = await GetListAPI(query);
    tableData.value = result.rows;
    state.total = result.total;
  } catch {
  } finally {
    state.loading = false;
  }
};
getList();

/**升温状态
 */
const warmingStatusChange = async (v) => {
  try {
    const isif = await proxy.MessageBox(
      `确定要${v.warmingStatus == 0 ? "开启" : "关闭"}升温状态吗？`
    );
    if (!isif) return;
    const res = await GetWarmingAPI({
      id: v.id,
      warmingStatus: v.warmingStatus,
    });
    proxy.successMsg("操作成功!");
  } catch (err) {
  } finally {
    getList();
  }
};

/**
 * 设备打印清空
 */

const printViewClose = () => {
  state.templateId = "";
};

/**
 * 监听 monitoringValue
 */
watch(
  () => useUserStore().gather,
  (v) => {
    console.log(gatherList.value.length, "---");
    if (gatherList.value.length != 100 && watchSwitch.value == 1) {
      gatherList.value.push(v);
    } else if (gatherList.value.length == 100 && watchSwitch.value == 1) {
      gatherList.value.pop();
      gatherList.value.push(v);
    }

    // fromList.value = v
  }
);
</script>

<template>
  <div class="app-container">
    <!-- 查询条件组件 -->
    <p-select-form :selectForm="selectList" @selectSubmit="selectSubmit" />
    <el-card class="box-card">
      <div class="flex">
        <div></div>

        <!-- 切换 -->
        <el-radio-group
          class="icon-chenge"
          v-model="tableType"
          @change="chengeTable"
        >
          <el-radio-button label="1">
            <el-icon>
              <Operation />
            </el-icon>
          </el-radio-button>

          <el-radio-button label="2">
            <el-icon>
              <Grid />
            </el-icon>
          </el-radio-button>
        </el-radio-group>
      </div>

      <p-table
        v-if="tableType == 1"
        :loading="state.loading"
        keyId="id"
        :column="column"
        :data="tableData"
        @change="handleSelectionChange"
        :total="state.total"
        v-model:page="query.pageNum"
        v-model:limit="query.pageSize"
        @pagination="getList"
      >
        <template #buttons>
          <!-- 按钮组件 -->
          <p-button
            :list="btnList"
            @add="addDic"
            @remove="batchRemove"
            @import="getList"
            :url="'/equipment/maintenance-project/itemExportError'"
            :templateUrl="'/system/device/download/excel'"
            :importUrl="'/equipment/maintenance-project/importData'"
          />
        </template>

        <template #columnCell="{ column, record }">
          <p-dictTag
            v-if="column.prop == 'deviceStatus'"
            :options="device_status"
            :value="record.deviceStatus"
          />
          <!-- <div v-if="column.prop == 'warmingStatus'">
            <el-switch
              v-model="record.warmingStatus"
              active-value="0"
              inactive-value="1"
              @click="warmingStatusChange(record)"
            />
          </div> -->
          <p-dictTag
            v-if="column.prop == 'equipmentOperationStatus'"
            :options="equipment_operation_status"
            :value="record.equipmentOperationStatus"
          />
          <p-operate
            v-if="column.prop == 'x'"
            :list="[
              {
                icon: 'Edit',
                emit: 'edit',
                text: '修改',
                type: 'primary',
                hasPermi: 'device:equipment:edit',
              },
              {
                icon: 'Delete',
                emit: 'remove',
                text: '删除',
                type: 'danger',
                hasPermi: 'device:equipment:remove',
              },
              {
                icon: 'Search',
                emit: 'look',
                text: '查看',
                type: 'primary',
                hasPermi: 'device:equipment:query',
              },
              {
                icon: 'Guide',
                emit: 'physicalModel',
                text: '数据模型',
                type: 'primary',
                hasPermi: 'device:equipment:physicalModel',
              },

              {
                icon: 'scaleToOriginal',
                emit: 'printDic',
                text: '设备打印',
                type: 'primary',
                hasPermi: 'device:equipment:print',
              },
            ]"
            @edit="editDic(record.id)"
            @gather="gatherDic(record)"
            @remove="remove(record.id)"
            @look="lookDic(record.id)"
            @physicalModel="physicalModelDic(record.id)"
            @printDic="printDic(record.id)"
          />
        </template>
        <!-- {
                icon: 'scaleToOriginal',
                emit: 'gather',
                text: '采集详情',
                type: 'primary',
                hasPermi: 'device:equipment:gather',
              }, -->
      </p-table>
      <el-row
        :gutter="20"
        v-if="tableType == 2"
        v-infinite-scroll="load"
        :infinite-scroll-disabled="loadDisabled"
      >
        <el-col :span="6" v-for="(t, i) in tableData" :key="i">
          <TextItem
            :item="t"
            @edit="editDic(t.id)"
            @remove="remove(t.id)"
            @view="lookDic(t.id)"
            @physicalModel="physicalModelDic(t.id)"
          />
        </el-col>
        <p v-if="state.loading" class="msg">加载中...</p>
        <p class="msg" v-if="noMore">数据已全部加载</p>
      </el-row>
      <!--  -->
    </el-card>
    <!-- 新增 -->
    <p-dialog
      v-model="state.isShow"
      :title="state.title"
      :loading="state.btnLoading"
      @close="close"
      @ok="state.title == '新增' ? addSub() : editSub()"
      width="65%"
    >
      <Form
        ref="formRef"
        :data="ruleForm"
        :title="state.title"
        :disabled="state.title == '查看'"
      />
    </p-dialog>

    <!-- 物模型 -->
    <p-dialog
      v-model="state.physicalModelShow"
      :title="state.title"
      :loading="state.btnLoading"
      okText="关闭"
      @close="state.physicalModelShow = false"
      @ok="state.physicalModelShow = false"
      width="60%"
    >
      <PhysicalModel
        ref="formRef"
        :data="ruleForm"
        :title="state.title"
        :disabled="state.title == '查看'"
      />
    </p-dialog>
    <!-- 数据采集 -->
    <p-dialog
      v-model="state.gatherShow"
      :title="'采集详情'"
      :loading="state.btnLoading"
      okText="关闭"
      @close="close"
      @ok="close"
      width="60%"
    >
      <p-select-form :selectForm="gatherSelect" @selectSubmit="gatherSubmit" />
      <div
        style="display: flex; justify-content: flex-end; align-items: center"
      >
        持续监听
        <el-switch
          v-model="watchSwitch"
          size="large"
          style="width: 100px"
          :active-value="1"
          :inactive-value="2"
          @change="watchChange"
        />
      </div>
      <div
        class="gather_list"
        v-infinite-scroll="loadGather"
        v-if="gatherList.length > 0"
      >
        <div
          v-for="(item, index) in gatherList"
          :key="index"
          class="gather_list_li"
        >
          <div class="Topic">Topic:{{ item.topic }}</div>

          <div style="margin: 10px 0px">采集时间:{{ item.ts }}</div>
          <div>采集信息:{{ item.msg }}</div>
        </div>
      </div>
      <!-- <p-table
        :loading="state.loading"
        keyId="id"
        :column="gatherColumn"
        :data="gatherData"
        :total="state.total"
        v-model:page="gatherQuery.pageNum"
        v-model:limit="gatherQuery.pageSize"
        @pagination="getgatherList"
      >
      </p-table> -->
    </p-dialog>

    <!-- 打印 -->
    <p-dialog
      v-model="state.printShow"
      title="设备打印"
      :loading="state.btnLoading"
      okText="打印"
      @close="printViewClose"
      @ok="printSub"
      width="60%"
    >
      <p-print-select v-model="state.templateId" :selectForm="gatherSelect" />
      <p-printView
        :templateId="state.templateId"
        :printData="ruleForm"
        ref="viewRef"
      />
    </p-dialog>
  </div>
</template>
<style scoped lang="scss">
.icon-chenge {
  float: right;
}

.Topic {
  color: #2d2929;
  font-size: 16px;
}

.flex {
  justify-content: space-between;
  align-items: center;
}

.msg {
  width: 100%;
  text-align: center;
  display: flex;
  justify-content: center;
  align-items: center;
}

.gather_list {
  height: 400px;
  overflow: hidden;
  overflow-y: auto;
}

.gather_list_li {
  background-color: #edeef3;
  color: #868687;
  // border-radius: 10px;
  border-top-right-radius: 10px;
  border-bottom-left-radius: 10px;
  border-bottom-right-radius: 10px;

  padding: 5px;
  margin-bottom: 10px;
  width: 300px;
}
</style>
